<?php

namespace App\Http\Controllers\Member;

use App\Models\Address;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AddressController extends Controller
{
    
    public function __construct()
    {

    }
    
    public function index()
    {
        $add=Address::where('user_id',auth()->user()->id)-> pluck('is_default')->toArray();
        if (!in_array(1,$add)){
            $sign=Address::where('user_id',auth()->user()->id)->first();
            $sign->is_default=1;
            $sign->save();
        }
        $address=Address::where('user_id',auth()->user()->id)-> get();
    return view('member.address.index',compact('address'));
    }
    public function create()
    {
        return view('member.address.create');
    }
    public function store(Request $request)
    {
       $request->validate([
           'name'=>'required',
           'phone'=>'required',
           'address'=>'required',
       ],[
           'name.required'=>'收件人姓名不能为空',
           'phone.required'=>'收件人手机不能为空',
           'address.required'=>'收件人地址不能为空',
       ]);
       if (isset($request->is_default)&&$request->is_default==1){
           $address=Address::where('is_default',1)->first();
           $address['is_default']=0;
           $address->save();
       }
        $request['user_id']=auth()->user()->id;
       Address::create($request->all());
       return redirect()->route('member.address.index')->with('success','添加地址成功');
    }

   
    public function show(Address $address)
    {
        //
    }
    
    public function edit(Address $address)
    {
        
        return view('member.address.edit',compact('address'));
    }

    public function update(Request $request, Address $address)
    {
        $request->validate([
            'name'=>'required',
            'phone'=>'required',
            'address'=>'required',
        ],[
            'name.required'=>'收件人姓名不能为空',
            'phone.required'=>'收件人手机不能为空',
            'address.required'=>'收件人地址不能为空',
        ]);
        if (isset($request->is_default)&&$request->is_default==1){
            $address=Address::where('is_default',1)->where('user_id',auth()->user()->id)->first();
            $address['is_default']=0;
            $address->save();
        }
        $request['user_id']=auth()->user()->id;
        $address->update($request->all());
        return redirect()->route('member.address.index')->with('success','编辑成功');
    }

    
    public function destroy(Address $address)
    {
        $address->delete();
        return back()->with('success','删除成功');
    }
    public function isDefault(Address $address){
        $add=Address::where('is_default',1)->where('user_id',auth()->user()->id)->first();
        $add['is_default']=0;
        $add->save();
        $address->is_default=1;
        $address->save();
        return back()->with('success','设置成功');
    }
}
